package com.hj.auth.common.handler;

import com.alibaba.fastjson.JSON;
import com.hj.common.constant.HttpStatus;
import com.hj.common.pojo.model.AjaxResult;
import com.hj.common.util.ServletUtils;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 请求失败处理器 : 用户未登陆
 */
@Component
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        int code = HttpStatus.UNAUTHORIZED;//401 : 未授权
        String msg = "请求访问: " + request.getRequestURI() +  "，认证失败, 未授权, 无法获取系统资源 !!!";
        ServletUtils.sendString(response, JSON.toJSONString(AjaxResult.error(code, msg)));
    }
}
